package com.example.myapplication

import android.app.PendingIntent
import android.content.Intent
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.session.MediaSession
import androidx.media3.session.MediaSessionService
import androidx.core.net.toUri
import android.os.Binder
import android.os.IBinder

class PlaybackService : MediaSessionService() {

    private var mediaSession: MediaSession? = null
    lateinit var player: ExoPlayer

    inner class LocalBinder : Binder() {
        fun getService(): PlaybackService = this@PlaybackService
    }
    private val binder = LocalBinder()

    override fun onCreate() {
        super.onCreate()

        player = ExoPlayer.Builder(this).build()
        mediaSession = MediaSession.Builder(this, player).build()

        player.addListener(object : Player.Listener {
            override fun onPlaybackStateChanged(playbackState: Int) {
                if (playbackState == Player.STATE_ENDED) {
                    handleAutoNext()
                }
            }
        })
    }

    private fun handleAutoNext() {
        val list = StaticStorage.playList
        if (list.isEmpty()) return

        var nextIndex = StaticStorage.playIndex

        when (StaticStorage.playMode) {
            PlayMode.REPEAT_ONE -> {
                playAudio(nextIndex)
            }
            PlayMode.REPEAT_ALL -> {
                nextIndex = (StaticStorage.playIndex + 1) % list.size
                updateIndexAndPlay(nextIndex)
            }
            PlayMode.SHUFFLE -> {
                nextIndex = list.indices.random()
                updateIndexAndPlay(nextIndex)
            }
            PlayMode.PLAY_ALL, PlayMode.REPEAT_NONE -> {
                if (StaticStorage.playIndex < list.size - 1) {
                    nextIndex = StaticStorage.playIndex + 1
                    updateIndexAndPlay(nextIndex)
                } else {
                    player.stop()
                }
            }
        }
    }

    private fun updateIndexAndPlay(index: Int) {
        StaticStorage.playIndex = index
        playAudio(index)
    }

    fun playAudio(index: Int) {
        if (index !in StaticStorage.playList.indices) return

        val file = StaticStorage.playList[index]
        val mediaItem = MediaItem.fromUri(file.absolutePath.toUri())

        player.setMediaItem(mediaItem)
        player.prepare()
        player.play()
    }

    fun seekTo(positionMs: Long) {
        player.seekTo(positionMs)
    }

    fun seekToRatio(ratio: Float) {
        if (ratio < 0f || ratio > 1f) return
        val duration = player.duration
        if (duration <= 0) return
        val positionMs = (ratio * duration).toLong()
        player.seekTo(positionMs)
    }

    override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? = mediaSession

    override fun onBind(intent: Intent?): IBinder? {
        super.onBind(intent)
        return binder
    }

    override fun onDestroy() {
        mediaSession?.run {
            player.release()
            release()
            mediaSession = null
        }
        super.onDestroy()
    }

    fun isAudioLoaded(): Boolean {
        return player.mediaItemCount > 0 &&
                player.playbackState != Player.STATE_IDLE
    }
}